import datetime
from flask import g, request, jsonify, current_app
from ihome import db, redis_store
from ihome.api_1_0 import api
from ihome.models import House, Order
from ihome.response_code import RET
from ihome.utils.commons import login_required


@api.route('/orders/<order_id>/comment', methods=['PUT'])
@login_required
def set_order_comment(order_id):
    """
    评论订单
    :param order_id:
    :return:
    """

    # 获取参数&校验参数
    params = request.get_json()
    comment = params.get('comment')
    if not comment:
        return jsonify(errno=RET.PARAMERR, errmsg='请输入评论内容')

    # 通过订单id查询出订单模型
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    # 更新数据
    house.order_count += 1
    order.status = "COMPLETE"
    order.comment = comment
    # 更新数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='更新数据库失败')

    # 删除redis中缓存的房屋详情信息，因为房屋详情信息已经更新
    try:
        redis_store.delete('house_info_' + house.id)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK')


@api.route('/orders/<order_id>/status', methods=['PUT'])
@login_required
def set_order_status(order_id):

    # 获取当前用户id
    user_id = g.user_id

    # 获取参数&校验参数
    params = request.get_json()
    action = params.get('action')
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 通过订单id查询出订单模型
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    # 判断订单是否存在并且当前房屋的用户id是当前用户id
    if not order or house.user_id != user_id:
        return jsonify(errno=RET.NODATA, errmsg='数据有误')

    if action == "accept":
        # 接单
        order.status = "WAIT_COMMENT"
    elif action == "reject":
        # 获取拒单原因
        reason = params.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='未填写拒单原因')

        # 设置状态为拒单并且设置拒单原因
        order.status = "REJECTED"
        order.comment = reason

    # 保存到数据库
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存订单状态失败')

    return jsonify(errno=RET.OK, errmsg='OK')


@api.route('/user/orders')
@login_required
def user_orders():
    """
    查询订单，通过参数判断要查询房东/房客的订单
    :return:
    """

    # 获取相关参数
    user_id = g.user_id
    role = request.args.get('role')

    if not role:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if role == "custom":
        # 查询当前自己下了哪些订单
        orders = Order.query.filter_by(user_id=user_id).order_by(Order.create_time.desc())
    else:
        # 查询自己房屋都有哪些订单
        houses = House.query.filter_by(user_id=user_id).all()
        house_ids = [houses.id for house in houses]
        orders = Order.query.filter(Order.house_id.in_(house_ids)).order_by(Order.create_time.desc())

    orders_dict = []

    for order in orders:
        orders_dict.append(order.to_dict())
    return jsonify(errno=RET.OK, errmsg='请求成功', data={"orders": orders_dict})


@api.route('/orders', methods=["POST"])
@login_required
def add_order():
    """
    添加订单
    :return:
    """

    # 获取当前用户id
    user_id = g.user_id
    # 获取到传入的参数
    params = request.get_json()
    house_id = params.get('house_id')
    start_date = params.get('start_date')
    end_date = params.get('end_date')

    # 校验参数
    if not all([house_id, start_date, end_date]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        start_date = datetime.datetime.strptime(start_date, "Y%-m%-d%")
        end_date = datetime.datetime.strptime(end_date, "Y%-m%-d%")
        if start_date and end_date:
            assert start_date < end_date, Exception("结束日期必须大于开始时间")
        # 计算出入住天数
        days = (end_date - start_date).days
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 判断房屋是否存在
    house = House.query.get(house_id)
    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    # 判断房屋是否是当前用户的
    if user_id == house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg='不能预订自己的房屋')

    # 查询是否存在冲突订单
    try:
        filters = [Order.house_id == house_id, Order.begin_date < end_date, Order.end_date > start_date]
        count = Order.query.filter(*filters).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg='该房屋已被预订')

    amount = days * house.price
    # 生成订单的模型
    order = Order()
    order.user_id = user_id
    order.house_id = house_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = amount

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')

    return jsonify(errno=RET.OK, errmsg='OK', data={"order_id": order.id})
